package com.rankeiot.platform.controller;

import com.rankeiot.core.Current;
import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.anno.DataScope;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.inner.argumet.QueryPage;
import com.rankeiot.core.inner.argumet.QueryParams;
import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.core.util.IDUtil;
import com.rankeiot.core.util.SqlScriptRunner;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.PlatformMenu;
import com.rankeiot.platform.domain.Branch;
import com.rankeiot.platform.domain.Codes;
import com.rankeiot.platform.service.CodesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.exception.DataAccessException;
import org.sagacity.sqltoy.model.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.StringReader;
import java.util.*;

/**
 * 编码规则
 **/
@Tag(name = "编码规则")
@Auth(PlatformMenu.CODES)
@RestController
@RequestMapping("codes")
@RequiredArgsConstructor
public class CodesController {
    final SqlToyLazyDao dao;
    final CodesService codesService;

    @Operation(summary = "新增编码规则")
    @Transactional
    @PostMapping("add")
    public Resp add(@Valid @RequestBody Codes codes) {

        codes.setAddTime(new Date());
        codes.setAddUser(Current.user().getUsername());
        codesService.saveRule(codes);
        return Resp.ok();
    }
    @Operation(summary = "获取所有配置的编码规则编号")
    @GetMapping("allCodes")
    public Resp allCodes(){
        String sql = "SELECT id FROM t_codes WHERE rules<>'[]'";
        List ids = dao.query().sql(sql).resultType(String.class).find();
        return Resp.of(ids);
    }
//    @Operation(summary = "判断是否有编码规则")
//    @PostMapping("hasRule")
//    public Resp hasRule(QueryParams params){
//        if (params.get("code") == null){
//            return Resp.of(false);
//        }
//        String code = params.get("code").toString();
//        String sql = "SELECT * FROM t_codes WHERE #[AND id = :id] limit 1";
//        Codes codes  = dao.loadBySql(sql, CollectionUtil.asMap("id",code),Codes.class);
//        if (codes == null || codes.getRules().isEmpty()){
//            return Resp.of(false);
//        }
//        return Resp.of(true);
//    }

    @Operation(summary = "删除编码规则")
    @PostMapping("delete")
    @Transactional
    public Resp delete(@RequestBody List<Codes> codesList) {
       // codesList = dao.loadAll(codesList);
        for(Codes c:codesList){
            codesService.deleteRule(c);
        }
        return Resp.ok();
    }

    @Operation(summary = "更新编码规则")
    @PostMapping("save")
    public Resp save(@Valid @RequestBody Codes codes) {
        codes.setAddTime(new Date());
        codes.setAddUser(Current.user().getUsername());
       codesService.updateRule(codes);
        return Resp.ok();
    }

    @Operation(summary = "获取编码规则列表")
    @RequestMapping("list")
    public Resp<List<Codes>> list(QueryPage query) {
       String sql= """
               SELECT * FROM t_codes WHERE #[AND id like :id] #[AND name like :name]
               """;
       try {
           Page result = dao.findPageBySql(query.page(), sql, query.params(), Codes.class);
           return Resp.of(result);
       }catch (DataAccessException e){
           if(e.getRootCause().getMessage().matches("Table '\\w+\\.t_codes' doesn't exist")){
               //创建表
               createTable();
           }else{
               throw e;
           }
           return Resp.of(query.page());
       }
    }
    @SneakyThrows
    private void createTable() {
        String createTableSql= """
                -- ----------------------------
                -- 流水号
                -- ----------------------------
                CREATE TABLE  IF NOT EXISTS  `t_max_no`  (
                    `no_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
                    `no_value` bigint(20) NULL DEFAULT NULL,
                    PRIMARY KEY (`no_name`) USING BTREE
                ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '最大编号' ROW_FORMAT = Dynamic;
                                
                -- ----------------------------
                -- 编码规则
                -- ----------------------------
                CREATE TABLE  IF NOT EXISTS  `t_codes`  (
                     `id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'ID',
                     `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '编码名称',
                     `memo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
                     `rules` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '规则',
                     `add_time` datetime NULL DEFAULT NULL COMMENT '添加时间',
                     `add_user` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '添加人',
                     `modify_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
                     `modify_user` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
                     PRIMARY KEY (`id`) USING BTREE
                ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '编码规则' ROW_FORMAT = Dynamic;               
                """;
        SqlScriptRunner scriptRunner= new  SqlScriptRunner(dao.getDataSource().getConnection());
        scriptRunner.runScript(new StringReader(createTableSql));
    }
}
